package com.elong.businesstravel.modules.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.debug.WriteLogCat;
import com.android.support.jhf.dialog.CustomWaitDialog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.network.loopj.android.http.TextHttpResponseHandler;
import com.android.support.jhf.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.android.support.jhf.utils.AndroidUniqueSerialNumber;
import com.android.support.jhf.utils.CoordinateConversion;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.FileUtils;
import com.android.support.jhf.utils.NetworkStatusUtils;
import com.android.support.jhf.onClick.OnClickListener;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption.LocationMode;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.activity.BaseActivity;
import com.elong.businesstravel.base.baidusdk.location.BaiduLocation;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.utils.AndroidManifestUtil;
import com.elong.businesstravel.base.utils.AppUserId;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.entitys.City;
import com.elong.businesstravel.entitys.Poi;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.modules.collect.HotelCollectActivity;
import com.elong.businesstravel.modules.help.HelpActivity;
import com.elong.businesstravel.modules.home.adapter.HotelLocationSelectAdapter;
import com.elong.businesstravel.modules.home.dialog.HotelPriceLevelDialog;
import com.elong.businesstravel.modules.login.LoginActivity;
import com.elong.businesstravel.modules.member.MemberCenterActivity;
import com.elong.businesstravel.modules.orders.OrdersActivity;
import com.elong.businesstravel.modules.orders.SendRecordCommentActivity;
import com.elong.businesstravel.protocol.baseresponse.BaseELongJsonHttpResponse;
import com.elong.businesstravel.protocol.baseresponse.IHttpResponse;
import com.elong.businesstravel.protocol.city.GetAllCityPoiRequest;
import com.elong.businesstravel.protocol.city.GetAllCityPoiResponse;
import com.elong.businesstravel.protocol.city.GetCityByLatLngRequest;
import com.elong.businesstravel.protocol.city.GetCityByLatLngResponse;
import com.elong.businesstravel.protocol.city.GetCityRequest;
import com.elong.businesstravel.protocol.city.GetCityResponse;
import com.elong.businesstravel.protocol.hotel.GuesshotelRequest;
import com.elong.businesstravel.protocol.hotel.GuesshotelResponse;
import com.elong.businesstravel.protocol.login.GetequipmentRequest;
import com.elong.businesstravel.protocol.login.GetequipmentResponse;
import com.elong.businesstravel.protocol.version.GetVersionRequest;
import com.elong.businesstravel.wxapi.WXEntryActivity;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.umeng.update.UmengUpdateAgent;

import android.R.string;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 差旅通首页
 * 
 * @author lenovo
 * 
 */
public class HomeActivity extends BaseActivity {

	private ViewGroup mCityNameLayout;
	private ViewGroup mLocationLayout;
	private ViewGroup mDateLayout;
	private ViewGroup mPriceLayout;

	private TextView mCityNameTextView;
	private TextView mPriceTextView;
	private TextView mLocationTextView;
	private TextView mDateTextView;

	// 保存状态
	private City mSaveCity = null;
	private ArrayList<Date> mSaveDates = null;
	private String mSavePriceLevel = null;
	private Poi mSavePoi = null;

	/** 开机定位 */
	private BaiduLocation mBootBaiduLocation;
	/** 附近 */
	private BaiduLocation mNearyBaiduLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		// 开启umeng推送
		PushAgent mPushAgent = PushAgent.getInstance(mContext);
		mPushAgent.enable();

		mApplication.mFlagHome = true;

		SaveUserOperate.setLastVersionCode(mContext, Version.versionCode + "");

		init();

	}

	protected void init() {

		umengSDKImploded();

		mCityNameLayout = (ViewGroup) findViewById(R.id.cityNameLayout);
		mLocationLayout = (ViewGroup) findViewById(R.id.locationLayout);
		mDateLayout = (ViewGroup) findViewById(R.id.dateLayout);
		mPriceLayout = (ViewGroup) findViewById(R.id.priceLayout);

		mCityNameTextView = (TextView) findViewById(R.id.cityNameTextView);
		mPriceTextView = (TextView) findViewById(R.id.priceTextView);
		mLocationTextView = (TextView) findViewById(R.id.locationTextView);
		mDateTextView = (TextView) findViewById(R.id.dateTextView);

		// 设置默认搜索条件，没有网络，没有缓存，只是显示
		setDefaultHotelSearchCondition();
		// 获取保存的信息
		getSaveHotelSearchCondition();
		// 设置保存的酒店搜索条件
		setSaveHotelSearchCondition();
		// 根据搜索条件设置显示的View
		setHotelSearchConditionView();

		setListener();

		if (null == mApplication.mCity) {
			getCityListRefreshView();
		}

		openAppLocation();

		// 用于下载所有城市的poi，开发时候用
		// getAllCityPoi();

		getequipment();

		if (!NetworkStatusUtils.networkStatusOK(mContext)) {
			showNetworkDialog();
		}
	}

	/**
	 * 如果没有连接网络显示对话框
	 */
	private void showNetworkDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("您的应用没有联网，请打开网络设置连接网络，或者设置应用的联网权限。");
		customAlertDialog.setLeftButton("知道了", new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	/**
	 * 打开软件定位
	 */
	private void openAppLocation() {
		mBootBaiduLocation = new BaiduLocation(mContext);
		mBootBaiduLocation.setLocationParams(LocationMode.Hight_Accuracy,
				false, 1000, true, "bd09ll", true);
		mBootBaiduLocation.setLocationListener(new BDLocationListener() {

			@Override
			public void onReceivePoi(BDLocation arg0) {

			}

			@Override
			public void onReceiveLocation(BDLocation arg0) {

				mBootBaiduLocation.stopLocation();

				if (null == arg0 || 0 == arg0.getLatitude()
						|| 0 == arg0.getLongitude() || null == arg0.getCity()
						|| "".equals(arg0.getCity())) {
					HandlerToastUI.getHandlerToastUI(mContext, "定位失败");
					hideWaitDialog();
					return;
				}

				mApplication.mBdLocation = arg0;

				double[] lngLat = CoordinateConversion.bd2gg(
						arg0.getLatitude(), arg0.getLongitude());

				getCityByLatLng(new IHttpResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								// 从新设置一次UI
								setLocationHotelSearchCondition();

								setHotelSearchConditionView();
							}
						});
					}
				}, lngLat[1], lngLat[0]);

			}
		});
		mBootBaiduLocation.startLocation();

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		if (null != intent) {
			String activityString = intent.getStringExtra("Activity");
			DebugLog.logI("HomeActivity onNewIntent : " + activityString);
		}
		DebugLog.logI("HomeActivity onNewIntent");
	}

	/**
	 * 友盟sdk集成
	 */
	private void umengSDKImploded() {
		// 自动更新
		UmengUpdateAgent.setUpdateAutoPopup(true);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(mApplication);

	}

	private void goMemberCenter() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, MemberCenterActivity.class);
			startActivity(intent);
		} else {
			// Intent intent = new Intent(mContext, WXEntryActivity.class);
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 4);
		}
	}

	/**
	 * 跳转到订单页
	 */
	private void goMemberOrders() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, OrdersActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		} else {
			// Intent intent = new Intent(mContext, WXEntryActivity.class);
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 5);
		}
	}

	/**
	 * 获取上次保存的酒店搜索条件
	 */
	private void getSaveHotelSearchCondition() {
		mSaveCity = SaveUserOperate.getHotelCity(mContext);
		mSaveDates = SaveUserOperate.getInOutHotelDates(mContext);
		checkInOutHotelDates();

		mSavePriceLevel = SaveUserOperate.getPriceLevel(mContext);
		mSavePoi = SaveUserOperate.getHotelLocation(mContext);
	}

	/**
	 * 核对从缓存中获取的时间
	 */
	private void checkInOutHotelDates() {
		if (null != mSaveDates && mSaveDates.size() > 0) {
			Date startDate = mSaveDates.get(0);

			String currentDateString = DateUtils.getCurrentDate("yyyyMMdd");
			String startDateString = DateUtils.dateFormat(startDate.getTime(),
					"yyyyMMdd");

			Date currentDate = new Date();
			currentDate.setTime(DateUtils.getDateMillis(currentDateString,
					"yyyyMMdd"));
			startDate.setTime(DateUtils.getDateMillis(startDateString,
					"yyyyMMdd"));

			if (currentDate.compareTo(startDate) > 0) {
				mSaveDates = null;
				SaveUserOperate.setInOutHotelDates(mContext,
						new ArrayList<Date>());
			}
		}
	}

	/**
	 * 设置保存酒店搜索条件
	 */
	private void setSaveHotelSearchCondition() {
		if (null != mSaveCity) {
			mApplication.mHotelSearchCondition.mSearchConditionCity = mSaveCity;
		}

		if (null != mSavePoi) {
			mApplication.mHotelSearchCondition.mSearchConditionPoi = mSavePoi;
		}

		mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition = 0;
		if (!TextUtils.isEmpty(mSavePriceLevel)) {
			for (int i = 0; i < mApplication.mPriceLevel.length; i++) {
				if (mApplication.mPriceLevel[i].equals(mSavePriceLevel)) {
					mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition = i;
					break;
				}
			}
		}

		if (null != mSaveDates && 0 != mSaveDates.size()) {
			mApplication.mHotelSearchCondition.mSearchConditionDate = DateUtils
					.dateFormat(mSaveDates.get(0).getTime(), "yyyy-MM-dd (E)");
			mApplication.mHotelSearchCondition.mSearchConditionDays = (mSaveDates
					.size() - 1) + "晚";
		}

	}

	/**
	 * 定位之后设置酒店搜索条件
	 */
	private void setLocationHotelSearchCondition() {

		if (null == mSaveCity && null != mApplication.mLocationCity) {
			// 当没有城市记录有定位的时候显示定位的城市
			mApplication.mHotelSearchCondition.mSearchConditionCity = mApplication.mLocationCity;
		}

		if (null == mSavePoi && null != mApplication.mBdLocation) {
			// 当没有poi记录的时候显示当前位置
			double[] lngLat = CoordinateConversion.bd2gg(
					mApplication.mBdLocation.getLatitude(),
					mApplication.mBdLocation.getLongitude());
			Poi poi = new Poi();
			poi.name = "当前位置";
			poi.googlelat = lngLat[1];
			poi.googlelng = lngLat[0];
			mApplication.mHotelSearchCondition.mSearchConditionPoi = poi;

		}

	}

	/**
	 * 设置默认酒店搜索条件，没有网络，没有缓存
	 */
	private void setDefaultHotelSearchCondition() {
		City city = new City();
		city.cityName = "北京";
		city.cityId = "0101";
		city.provinceId = "0100";
		city.firstCode = "B";
		city.allCode = "beijing";
		city.sorts = "3239";
		mApplication.mHotelSearchCondition.mSearchConditionCity = city;

		Poi poi = new Poi();
		poi.name = HotelLocationSelectAdapter.NO_LIMIT;
		mApplication.mHotelSearchCondition.mSearchConditionPoi = poi;

		mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition = 0;

		mApplication.mHotelSearchCondition.mSearchConditionDate = mApplication.mHotelDestineDateStrings[0];
		mApplication.mHotelSearchCondition.mSearchConditionDays = "1晚";
	}

	/**
	 * 用来设置酒店搜索条件的显示View
	 */
	private void setHotelSearchConditionView() {

		if (null != mApplication.mLocationCity
				&& mApplication.mHotelSearchCondition.mSearchConditionCity.cityName
						.equals(mApplication.mLocationCity.cityName)) {
			mCityNameTextView
					.setText(mApplication.mHotelSearchCondition.mSearchConditionCity.cityName
							+ "(当前)");
		} else {
			mCityNameTextView
					.setText(mApplication.mHotelSearchCondition.mSearchConditionCity.cityName);
		}

		mPriceTextView
				.setText(mApplication.mPriceLevel[mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition]);

		String dateString = DateUtils.dateFormat(DateUtils.getDateMillis(
				mApplication.mHotelSearchCondition.mSearchConditionDate,
				"yyyy-MM-dd (E)"), "MM/dd");
		mDateTextView.setText(dateString + " 住"
				+ mApplication.mHotelSearchCondition.mSearchConditionDays);

		String nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.name;
		if (TextUtils.isEmpty(nameString)) {
			nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.bussinename;
		}
		if (TextUtils.isEmpty(nameString)) {
			nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.districtsname;
		}
		mLocationTextView.setText(nameString);
	}

	/**
	 * 定位之后联网获取城市实体
	 * 
	 * @param latString
	 * @param lngString
	 */
	private void getCityByLatLng(final IHttpResponse iHttpResponse,
			final double latString, final double lngString) {
		NetworkClient.getNetworkClient().PostRequest(
				new GetCityByLatLngRequest(mContext, latString, lngString),
				new GetCityByLatLngResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {

						mApplication.mLocationCity = ((GetCityByLatLngResponse) responseHandlerInterface).mCity;

						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}

						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {

								hideWaitDialog();

							}
						});
					}
				}, new BaseStateListener() {
					@Override
					public void onFinish(AsyncHttpRequest asyncHttpRequest) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								hideWaitDialog();

							}
						});

					}
				}, new BaseErrorListener() {
				});
	}

	/**
	 * 获取城市列表刷新界面
	 */
	private void getCityListRefreshView() {
		getCityList(new IHttpResponse() {

			@Override
			public void onResponse(
					ResponseHandlerInterface responseHandlerInterface) {
				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
					}
				});
			}
		});
	}

	/**
	 * 获取城市列表
	 * 
	 * @param iHttpResponse
	 */
	private void getCityList(final IHttpResponse iHttpResponse) {

		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetCityRequest getCityRequest = new GetCityRequest(mContext);
		final String cacheKeyString = getCacheDir() + "/"
				+ md5FileNameGenerator.generate(getCityRequest.getCacheKey());

		NetworkClient.getNetworkClient().PostRequest(getCityRequest,
				new GetCityResponse() {
					@Override
					public void onResponse(
							final ResponseHandlerInterface responseHandlerInterface) {
						mApplication.mCity = ((GetCityResponse) responseHandlerInterface).mCity;
						String responseString = ((GetCityResponse) responseHandlerInterface).responseString;
						FileUtils.saveFile(responseString, new File(
								cacheKeyString));
						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}
					}
				});
	}

	/**
	 * 跳转城市
	 */
	private void goHotelCitySelectActivity() {
		if (null != mApplication.mCity) {
			Intent intent = new Intent(mContext, HotelCitySelectActivity.class);
			startActivityForResult(intent, 0);
			overridePendingTransition(
					R.anim.activity_bottom_top_enter_anim_translate,
					R.anim.activity_alpha_fixed);
		} else {
			getCityList(new IHttpResponse() {

				@Override
				public void onResponse(
						ResponseHandlerInterface responseHandlerInterface) {
					HandlerPostUI.getHandlerPostUI(new Runnable() {

						@Override
						public void run() {
							Intent intent = new Intent(mContext,
									HotelCitySelectActivity.class);
							startActivityForResult(intent, 0);
							overridePendingTransition(
									R.anim.activity_bottom_top_enter_anim_translate,
									R.anim.activity_alpha_fixed);

						}
					});
				}
			});
		}
	}

	/**
	 * 跳转到附近酒店
	 */
	private void goNearbyHotel() {
		showWaitDialog("正在定位...", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				mNearyBaiduLocation.stopLocation();
			}
		});

		mNearyBaiduLocation = new BaiduLocation(mContext);
		mNearyBaiduLocation.setLocationParams(LocationMode.Hight_Accuracy,
				false, 1000, true, "bd09ll", true);
		mNearyBaiduLocation.setLocationListener(new BDLocationListener() {

			@Override
			public void onReceivePoi(BDLocation arg0) {

			}

			@Override
			public void onReceiveLocation(BDLocation arg0) {

				mNearyBaiduLocation.stopLocation();

				if (null == arg0 || 0 == arg0.getLatitude()
						|| 0 == arg0.getLongitude()
						|| TextUtils.isEmpty(arg0.getCity())) {
					HandlerToastUI.getHandlerToastUI(mContext, "定位失败");
					hideWaitDialog();
					return;
				}

				mApplication.mBdLocation = arg0;

				double[] lngLat = CoordinateConversion.bd2gg(
						arg0.getLatitude(), arg0.getLongitude());

				getCityByLatLng(new IHttpResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {

						double[] lngLat = CoordinateConversion.bd2gg(
								mApplication.mBdLocation.getLatitude(),
								mApplication.mBdLocation.getLongitude());

						Intent intent = new Intent(mContext,
								HotelSearchResultActivity.class);
						intent.putExtra("sort", mApplication.mHotelLocSorts);
						intent.putExtra("sorts", "4");
						intent.putExtra("PoiName", "当前位置");
						intent.putExtra("googlelat", lngLat[1]);
						intent.putExtra("googlelng", lngLat[0]);
						intent.putExtra("LocationCity",
								mApplication.mLocationCity);
						startActivity(intent);
					}
				}, lngLat[1], lngLat[0]);

			}
		});
		mNearyBaiduLocation.startLocation();

		// getLocation(new IHttpResponse() {
		//
		// @Override
		// public void onResponse(
		// ResponseHandlerInterface responseHandlerInterface) {
		//
		// double[] lngLat = CoordinateConversion.bd2gg(
		// mApplication.mBdLocation.getLatitude(),
		// mApplication.mBdLocation.getLongitude());
		//
		// Intent intent = new Intent(mContext,
		// HotelSearchResultActivity.class);
		// intent.putExtra("sort", mApplication.mHotelLocSorts);
		// intent.putExtra("sorts", "4");
		// intent.putExtra("PoiName", "当前位置");
		// intent.putExtra("googlelat", lngLat[1]);
		// intent.putExtra("googlelng", lngLat[0]);
		// intent.putExtra("LocationCity", mApplication.mLocationCity);
		// startActivity(intent);
		// }
		// });
	}

	private void goHotelCollectActivity() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, HotelCollectActivity.class);
			startActivity(intent);
		} else {
			// Intent intent = new Intent(mContext, WXEntryActivity.class);
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 6);
		}
	}

	protected void setListener() {
		Button collectButton = (Button) findViewById(R.id.collectButton);
		collectButton.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goHotelCollectActivity();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		Button nearbyButton = (Button) findViewById(R.id.nearbyButton);
		nearbyButton.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goNearbyHotel();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		mCityNameLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onFastDoubleClick(View v) {
				goHotelCitySelectActivity();
			}
		});
		mLocationLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onFastDoubleClick(View v) {
				Intent intent = new Intent(mContext,
						HotelLocationSelectActivity.class);
				intent.putExtra("city",
						mApplication.mHotelSearchCondition.mSearchConditionCity);
				startActivityForResult(intent, 2);
				overridePendingTransition(
						R.anim.activity_bottom_top_enter_anim_translate,
						R.anim.activity_alpha_fixed);
			}
		});
		mDateLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onFastDoubleClick(View v) {
				Intent intent = new Intent(mContext,
						HotelDestineDateActivity.class);
				intent.putExtra("select",
						mApplication.mHotelSearchCondition.mSearchConditionDate);
				startActivityForResult(intent, 3);
				overridePendingTransition(
						R.anim.activity_bottom_top_enter_anim_translate,
						R.anim.activity_alpha_fixed);
			}
		});
		mPriceLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onFastDoubleClick(View v) {

				hotelPriceLevelDialog();
			}
		});

		Button memberButton = (Button) findViewById(R.id.memberButton);
		memberButton.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goMemberCenter();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		Button ordersButton = (Button) findViewById(R.id.ordersButton);
		ordersButton.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goMemberOrders();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ImageView hotelSearchImageView = (ImageView) findViewById(R.id.hotelSearchButton);
		hotelSearchImageView
				.setOnClickListener(new OnClickNetworkStatusListener(mContext) {

					@Override
					public void onClickNetworkSucceed(View view) {

						if (null != mApplication.mBdLocation
								&& "当前位置"
										.equals(mApplication.mHotelSearchCondition.mSearchConditionPoi.name)) {
							double[] lngLat = CoordinateConversion.bd2gg(
									mApplication.mBdLocation.getLatitude(),
									mApplication.mBdLocation.getLongitude());

							Intent intent = new Intent(mContext,
									HotelSearchResultActivity.class);
							intent.putExtra("sort", mApplication.mHotelLocSorts);
							intent.putExtra("sorts", "4");
							intent.putExtra("PoiName", "当前位置");
							intent.putExtra("googlelat", lngLat[1]);
							intent.putExtra("googlelng", lngLat[0]);
							intent.putExtra("LocationCity",
									mApplication.mLocationCity);
							startActivity(intent);
						} else {
							Intent intent = new Intent(mContext,
									HotelSearchResultActivity.class);
							intent.putExtra("sort", mApplication.mHotelSorts);
							startActivity(intent);
						}

					}

					@Override
					public void onClickNetworkFail(View view) {

					}
				});

		Button helpButton = (Button) findViewById(R.id.helpButton);
		helpButton
				.setOnClickListener(new OnClickNetworkStatusListener(mContext) {

					@Override
					public void onClickNetworkSucceed(View view) {
						Intent intent = new Intent(mContext, HelpActivity.class);
						startActivity(intent);
					}

					@Override
					public void onClickNetworkFail(View view) {

					}
				});

	}

	private void hotelPriceLevelDialog() {
		final HotelPriceLevelDialog hotelPriceLevelDialog = new HotelPriceLevelDialog(
				mContext,
				com.android.support.jhf.R.style.DialogFromDownToUp,
				mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition);
		hotelPriceLevelDialog.setOnItemListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// 保存缓存
				String priceLevelString = (String) arg1.getTag();
				SaveUserOperate.setPriceLevel(mContext, priceLevelString);

				mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition = arg2;

				mPriceTextView
						.setText(mApplication.mPriceLevel[mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition]);

				hotelPriceLevelDialog.cancel();

			}
		});
		hotelPriceLevelDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 选择城市返回
			switch (resultCode) {
			case RESULT_OK: {
				City city = (City) data.getSerializableExtra("city");
				mApplication.mHotelSearchCondition.mSearchConditionCity = city;
				if (null != mApplication.mLocationCity
						&& mApplication.mHotelSearchCondition.mSearchConditionCity.cityName
								.equals(mApplication.mLocationCity.cityName)) {
					mCityNameTextView
							.setText(mApplication.mHotelSearchCondition.mSearchConditionCity.cityName
									+ "(当前)");
				} else {
					mCityNameTextView
							.setText(mApplication.mHotelSearchCondition.mSearchConditionCity.cityName);
				}
				mCityNameTextView.setText(city.cityName);

				// 修改城市poi清空
				Poi poi = new Poi();
				poi.name = HotelLocationSelectAdapter.NO_LIMIT;
				mApplication.mHotelSearchCondition.mSearchConditionPoi = poi;
				mLocationTextView.setText(poi.name);
				SaveUserOperate.setHotelLocation(mContext, poi);
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 1: {
			// 选择价格/星级
			switch (resultCode) {
			case RESULT_OK: {
				mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition = data
						.getIntExtra("priceLevelValuePosition", 0);

				mPriceTextView
						.setText(mApplication.mPriceLevel[mApplication.mHotelSearchCondition.mSearchConditionPriceValuePosition]);
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 2: {
			// 选择位置返回
			switch (resultCode) {
			case RESULT_OK: {
				mApplication.mHotelSearchCondition.mSearchConditionPoi = (Poi) data
						.getSerializableExtra("Poi");
				SaveUserOperate.setHotelLocation(mContext,
						mApplication.mHotelSearchCondition.mSearchConditionPoi);
				String nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.name;
				if ("".equals(nameString)) {
					nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.bussinename;
				}
				if ("".equals(nameString)) {
					nameString = mApplication.mHotelSearchCondition.mSearchConditionPoi.districtsname;
				}
				mLocationTextView.setText(nameString);
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 3: {
			// 入住酒店时间和天数
			switch (resultCode) {
			case RESULT_OK: {
				mApplication.mHotelSearchCondition.mSearchConditionDate = data
						.getStringExtra("date");
				mApplication.mHotelSearchCondition.mSearchConditionDays = data
						.getStringExtra("days");
				String dateString = DateUtils
						.dateFormat(
								DateUtils
										.getDateMillis(
												mApplication.mHotelSearchCondition.mSearchConditionDate,
												"yyyy-MM-dd (E)"), "MM/dd");
				mDateTextView
						.setText(dateString
								+ " 住"
								+ mApplication.mHotelSearchCondition.mSearchConditionDays);
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 4: {
			// 登陆返回,跳转到会员中心
			switch (resultCode) {
			case RESULT_OK: {
				goMemberCenter();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 5: {
			// 登陆返回,跳转到查看订单
			switch (resultCode) {
			case RESULT_OK: {
				goMemberOrders();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 6: {
			// 登陆返回，跳转到收藏
			switch (resultCode) {
			case RESULT_OK: {
				goHotelCollectActivity();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	private void quit() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("是否退出应用");
		customAlertDialog.setLeftButton("是", new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// WriteLogCat.factory().stopLogCarInfo();
				finish();
				System.exit(0);
			}
		});
		customAlertDialog.setRightButton("否", new View.OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		customAlertDialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// private void getVersion() {
	// NetworkClient.getNetworkClient().PostRequest(
	// new GetVersionRequest(mContext), new BaseJsonHttpResponse() {
	//
	// @Override
	// public void onSuccess(int statusCode, Header[] headers,
	// String responseString) {
	// // try {
	// // JSONObject jsonObject = new
	// // JSONObject(responseString);
	// // HandlerToastUI.getHandlerToastUI(mContext,
	// // jsonObject.getString("resultdes"));
	// // } catch (JSONException e) {
	// // e.printStackTrace();
	// // }
	//
	// }
	//
	// });
	//
	// }

	/**
	 * 用于下载所有城市的poi，开发时候用
	 */
	private void getAllCityPoi() {
		NetworkClient.getNetworkClient().PostRequest(
				new GetAllCityPoiRequest(mContext),
				new GetAllCityPoiResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
					}

				});

	}

	/**
	 * 每次都需要刷新搜索条件的日期
	 */
	private void refreshDate() {
		// 从缓存中取
		mSaveDates = SaveUserOperate.getInOutHotelDates(mContext);
		checkInOutHotelDates();
		// 设置默认
		mApplication.mHotelSearchCondition.mSearchConditionDate = mApplication.mHotelDestineDateStrings[0];
		mApplication.mHotelSearchCondition.mSearchConditionDays = "1晚";
		// 缓存有效设置缓存
		if (null != mSaveDates && 0 != mSaveDates.size()) {
			mApplication.mHotelSearchCondition.mSearchConditionDate = DateUtils
					.dateFormat(mSaveDates.get(0).getTime(), "yyyy-MM-dd (E)");
			mApplication.mHotelSearchCondition.mSearchConditionDays = (mSaveDates
					.size() - 1) + "晚";
		}
		// 更新显示
		String dateString = DateUtils.dateFormat(DateUtils.getDateMillis(
				mApplication.mHotelSearchCondition.mSearchConditionDate,
				"yyyy-MM-dd (E)"), "MM/dd");
		mDateTextView.setText(dateString + " 住"
				+ mApplication.mHotelSearchCondition.mSearchConditionDays);
	}

	/**
	 * 发送用于推送的token
	 */
	private void getequipment() {
		String device_token = UmengRegistrar.getRegistrationId(mContext);
		NetworkClient.getNetworkClient().PostRequest(
				new GetequipmentRequest(mContext, device_token),
				new GetequipmentResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						super.onResponse(responseHandlerInterface);

					}
				}, new BaseStateListener() {
				}, new BaseErrorListener() {
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshDate();
		wechatLoginGoActivity();
	}

	/**
	 * 微信联合登陆返回跳转到相应界面
	 */
	private void wechatLoginGoActivity() {
		// if(mApplication.mFlagWeChat){
		// DebugLog.logI("微信登陆成功");
		// mApplication.mFlagWeChat = false;
		// }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// HandlerToastUI.getHandlerToastUI(mContext, "onSaveInstanceState");
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		// HandlerToastUI.getHandlerToastUI(mContext, "onRestoreInstanceState");
	}

}
